import { defineStore } from 'pinia'
import { login as loginApi } from '@/api/user'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { TOKEN_EXPIRE_TIME, TOKEN_CHECK_INTERVAL } from '@/constants/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    loginTime: localStorage.getItem('loginTime') || null
  }),

  getters: {
    isLogin: (state) => !!state.token,

    // 判断是否有某个权限
    hasPermission: (state) => (permission) => {
      return state.userInfo.permissions.includes(permission)
    }
  },

  actions: {
    // 设置token
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },

    // 登录
    async login(loginForm) {
      try {
        const res = await loginApi(loginForm)
        this.setToken(res.data.token)
        this.setUserInfo(res.data.userInfo)

        // 设置3分钟后过期
        const expireTime = new Date().getTime() + 50 * 60 * 1000
        localStorage.setItem('expireTime', expireTime)

        ElMessage.success('登录成功')
        router.push('/')
        return res
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },

    // 退出登录
    logout() {
      this.token = ''
      this.userInfo = {}
      this.loginTime = null
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('loginTime')
      localStorage.removeItem('expireTime')
      router.push('/login')
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await axios.get('/api/user/info')
        this.setUserInfo(response.data.data)
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.clearUserInfo()
      }
    },

    // 清除用户信息
    clearUserInfo() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      delete axios.defaults.headers.common['Authorization']
    },

    // 检查token是否过期
    checkToken() {
      const loginTime = parseInt(this.loginTime)
      if (!loginTime) return true

      const now = new Date().getTime()
      const isExpired = now - loginTime > TOKEN_EXPIRE_TIME

      if (isExpired) {
        ElMessage.warning('登录已过期，请重新登录')
        this.logout()
      }
      return isExpired
    },

    // 启动定时检查
    startTokenCheck() {
      setInterval(() => {
        this.checkToken()
      }, TOKEN_CHECK_INTERVAL)
    }
  }
})
